package com.example.summary.controller;


import okhttp3.*;

import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * Created by ${zhangdi} on 2017/11/22.
 */
public class OkHttpUtil {
    private static final OkHttpClient builderClient = new OkHttpClient();

    public static String sendXmlPost(String traceId, String url, String param, boolean isBreak) {
        return sendXmlPost(traceId, url, param, 1000, 1000, "utf-8", "utf-8", isBreak);
    }

    public static String sendXmlGet(String traceId, String url, boolean isBreak) {
        return sendXmlGet(traceId, url, 1000, 1000, "utf-8", "utf-8", isBreak);
    }

    public static String sendJsonPost(String traceId, String url, String json, boolean isBreak) {
        return sendJsonPost(traceId, url, json, 1000, 1000, "utf-8", "utf-8", isBreak);
    }

    public static String sendJsonGet(String traceId, String url, boolean isBreak) {
        return sendJsonGet(traceId, url, 1000, 1000, "utf-8", "utf-8", isBreak);
    }

    public static String sendTextPost(String traceId, String url, String param, boolean isBreak) {
        return sendTextPost(traceId, url, param, 1000, 1000, "utf-8", "utf-8", isBreak);
    }

    public static String sendTextPost(String traceId, String url, String param, Map<String, String> header, boolean isBreak) {
        return sendTextPost(traceId, url, param, header, 1000, 1000, "utf-8", "utf-8", isBreak);
    }

    public static String sendTextGet(String traceId, String url, boolean isBreak) {
        return sendTextGet(traceId, url, 1000, 1000, "utf-8", "utf-8", isBreak);
    }

    public static String sendKVJsonPost(String traceId, String url, Map<String, String> kv, boolean isBreak) {
        return sendKVJsonPost(traceId, url, kv, 1000, 1000, "utf-8", "utf-8", isBreak);
    }

    public static String sendKVTextPost(String traceId, String url, Map<String, String> kv, boolean isBreak) {
        return sendKVTextPost(traceId, url, kv, 1000, 1000, "utf-8", "utf-8", isBreak);
    }

    /**
     * @param traceId
     * @param url                        请求url 带参数的
     * @param connectTimeoutMilliSeconds 连接超时毫秒数
     * @param readTimeoutMilliSeconds    读取超时毫秒数
     * @param reqCharset                 请求字符集
     * @param resCharset                 响应字符集
     * @param isBreak                    是否支持紧急情况下的手动熔断 和项目的comm配置文件中的request.break=true合并生效
     * @return
     */
    public static String sendXmlGet(String traceId, String url, long connectTimeoutMilliSeconds, long readTimeoutMilliSeconds,
                                    String reqCharset, String resCharset, boolean isBreak) {
        try {
            if (isBreakRequest() && isBreak) {
                return "";
            }
            OkHttpClient client = builderClient.newBuilder().connectTimeout(connectTimeoutMilliSeconds, TimeUnit.MILLISECONDS).
                    readTimeout(readTimeoutMilliSeconds, TimeUnit.MILLISECONDS).build();

            Request request = new Request.Builder()
                    .url(url)
                    .header("Pragma", "no-cache")
                    .addHeader("Cache-Control", "no-cache")
                    .addHeader("Content-Type", "text/xml;charset=" + reqCharset)
                    .get()
                    .build();
            Response response = client.newCall(request).execute(); //execute 同步执行
            return new String(response.body().bytes(), resCharset);
        } catch (Exception e) {
            
        }
        return "";
    }

    /**
     * @param traceId
     * @param url                        请求url
     * @param param                      参数
     * @param connectTimeoutMilliSeconds 连接超时毫秒数
     * @param readTimeoutMilliSeconds    读取超时毫秒数
     * @param reqCharset                 请求字符集
     * @param resCharset                 响应字符集
     * @param isBreak                    是否支持紧急情况下的手动熔断 和项目的comm配置文件中的request.break=true合并生效
     * @return
     */
    public static String sendXmlPost(String traceId, String url, String param, long connectTimeoutMilliSeconds, long readTimeoutMilliSeconds,
                                     String reqCharset, String resCharset, boolean isBreak) {
        try {
            if (isBreakRequest() && isBreak) {
                return "";
            }
            OkHttpClient client = builderClient.newBuilder().connectTimeout(connectTimeoutMilliSeconds, TimeUnit.MILLISECONDS).
                    readTimeout(readTimeoutMilliSeconds, TimeUnit.MILLISECONDS).build();
            RequestBody body = RequestBody.create(MediaType.parse("text/xml"), param.getBytes(reqCharset));
            Request request = new Request.Builder()
                    .url(url)
                    .header("Pragma", "no-cache")
                    .addHeader("Cache-Control", "no-cache")
                    .addHeader("Content-Type", "text/xml;charset=" + reqCharset)
                    .post((okhttp3.RequestBody) body)
                    .build();
            Response response = client.newCall(request).execute(); //execute 同步执行
            return new String(response.body().bytes(), resCharset);
        } catch (Exception e) {
        }
        return "";
    }

    /**
     * @param traceId
     * @param url                        请求url
     * @param json                       json参数
     * @param connectTimeoutMilliSeconds 连接超时毫秒数
     * @param readTimeoutMilliSeconds    读取超时毫秒数
     * @param reqCharset                 请求字符集
     * @param resCharset                 响应字符集
     * @param isBreak                    是否支持紧急情况下的手动熔断 和项目的comm配置文件中的request.break=true合并生效
     * @return
     */
    public static String sendJsonPost(String traceId, String url, String json, long connectTimeoutMilliSeconds,
                                      long readTimeoutMilliSeconds,
                                      String reqCharset, String resCharset, boolean isBreak) {
        try {
            if (isBreakRequest() && isBreak) {
                return "";
            }
            OkHttpClient client = builderClient.newBuilder().connectTimeout(connectTimeoutMilliSeconds, TimeUnit.MILLISECONDS).
                    readTimeout(readTimeoutMilliSeconds, TimeUnit.MILLISECONDS).build();
            RequestBody body = RequestBody.create(MediaType.parse("application/json"), json.getBytes(reqCharset));
            Request request = new Request.Builder()
                    .url(url)
                    .header("X-FORMAT", "json")
                    .addHeader("Content-Type", "application/json; charset=" + reqCharset)
                    .post(body)
                    .build();
            Response response = client.newCall(request).execute(); //execute 同步执行
            return new String(response.body().bytes(), resCharset);
        } catch (Exception e) {
        }
        return "";
    }

    /**
     * @param traceId
     * @param url                        请求url带参数的
     * @param connectTimeoutMilliSeconds 连接超时毫秒数
     * @param readTimeoutMilliSeconds    读取超时毫秒数
     * @param reqCharset                 请求字符集
     * @param resCharset                 响应字符集
     * @param isBreak                    是否支持紧急情况下的手动熔断 和项目的comm配置文件中的request.break=true合并生效
     * @return
     */
    public static String sendJsonGet(String traceId, String url, long connectTimeoutMilliSeconds,
                                     long readTimeoutMilliSeconds,
                                     String reqCharset, String resCharset, boolean isBreak) {
        try {
            if (isBreakRequest() && isBreak) {
                return "";
            }
            OkHttpClient client = builderClient.newBuilder().connectTimeout(connectTimeoutMilliSeconds, TimeUnit.MILLISECONDS).
                    readTimeout(readTimeoutMilliSeconds, TimeUnit.MILLISECONDS).build();
            Request request = new Request.Builder()
                    .url(url)
                    .header("X-FORMAT", "json")
                    .addHeader("Content-Type", "application/json; charset=" + reqCharset)
                    .get()
                    .build();
            Response response = client.newCall(request).execute(); //execute 同步执行
            return new String(response.body().bytes(), resCharset);
        } catch (Exception e) {
            
        }
        return "";
    }

    /**
     * @param traceId
     * @param url                        请求url
     * @param kv                         键值对参数
     * @param connectTimeoutMilliSeconds 连接超时毫秒数
     * @param readTimeoutMilliSeconds    读取超时毫秒数
     * @param reqCharset                 请求字符集
     * @param resCharset                 响应字符集
     * @param isBreak                    是否支持紧急情况下的手动熔断 和项目的comm配置文件中的request.break=true合并生效
     * @return
     */
    public static String sendKVJsonPost(String traceId, String url, Map<String, String> kv, long connectTimeoutMilliSeconds,
                                        long readTimeoutMilliSeconds, String reqCharset, String resCharset, boolean isBreak) {
        try {
            if (isBreakRequest() && isBreak) {
                return "";
            }
            OkHttpClient client = builderClient.newBuilder().connectTimeout(connectTimeoutMilliSeconds, TimeUnit.MILLISECONDS).
                    readTimeout(readTimeoutMilliSeconds, TimeUnit.MILLISECONDS).build();
            FormBody.Builder formBodyBuilder = new FormBody.Builder();
            for (Map.Entry<String, String> entry : kv.entrySet()) {
                formBodyBuilder.add(entry.getKey(), entry.getValue());
            }
            FormBody body = formBodyBuilder.build();
            Request request = new Request.Builder()
                    .url(url)
                    .header("X-FORMAT", "json")
                    .addHeader("Content-Type", "application/json; charset=" + reqCharset)
                    .post(body)
                    .build();
            Response response = client.newCall(request).execute(); //execute 同步执行

            return new String(response.body().bytes(), resCharset);

        } catch (Exception e) {
        }
        return "";
    }

    /**
     * @param traceId
     * @param url                        请求url
     * @param kv                         键值对参数
     * @param connectTimeoutMilliSeconds 连接超时毫秒数
     * @param readTimeoutMilliSeconds    读取超时毫秒数
     * @param reqCharset                 请求字符集
     * @param resCharset                 响应字符集
     * @param isBreak                    是否支持紧急情况下的手动熔断 和项目的comm配置文件中的request.break=true合并生效
     * @return
     */
    public static String sendKVTextPost(String traceId, String url, Map<String, String> kv, long connectTimeoutMilliSeconds,
                                        long readTimeoutMilliSeconds, String reqCharset, String resCharset, boolean isBreak) {
        try {
            if (isBreakRequest() && isBreak) {
                return "";
            }
            OkHttpClient client = builderClient.newBuilder().connectTimeout(connectTimeoutMilliSeconds, TimeUnit.MILLISECONDS).
                    readTimeout(readTimeoutMilliSeconds, TimeUnit.MILLISECONDS).build();
            FormBody.Builder formBodyBuilder = new FormBody.Builder();
            for (Map.Entry<String, String> entry : kv.entrySet()) {
                formBodyBuilder.add(entry.getKey(), entry.getValue());
            }
            FormBody body = formBodyBuilder.build();

            Request request = new Request.Builder()
                    .url(url)
                    .addHeader("Content-Type", "text/plain; charset=" + reqCharset)
                    .post(body)
                    .build();
            Response response = client.newCall(request).execute(); //execute 同步执行

            return new String(response.body().bytes(), resCharset);

        } catch (Exception e) {
        }
        return "";
    }

    /**
     * @param traceId
     * @param url                        请求url
     * @param param                      参数
     * @param connectTimeoutMilliSeconds 连接超时毫秒数
     * @param readTimeoutMilliSeconds    读取超时毫秒数
     * @param reqCharset                 请求字符集
     * @param resCharset                 响应字符集
     * @param isBreak                    是否支持紧急情况下的手动熔断 和项目的comm配置文件中的request.break=true合并生效
     * @return
     */
    public static String sendTextPost(String traceId, String url, String param, long connectTimeoutMilliSeconds,
                                      long readTimeoutMilliSeconds, String reqCharset, String resCharset, boolean isBreak) {
        try {
            if (isBreakRequest() && isBreak) {
                return "";
            }
            OkHttpClient client = builderClient.newBuilder().connectTimeout(connectTimeoutMilliSeconds, TimeUnit.MILLISECONDS).
                    readTimeout(readTimeoutMilliSeconds, TimeUnit.MILLISECONDS).build();
            RequestBody body = RequestBody.create(MediaType.parse("text/plain; charset=" + reqCharset), param.getBytes(reqCharset));
            Request request = new Request.Builder()
                    .url(url)
                    .addHeader("Content-Type", "text/plain; charset=" + reqCharset)
                    .post(body)
                    .build();
            Response response = client.newCall(request).execute(); //execute 同步执行
            return new String(response.body().bytes(), resCharset);
        } catch (Exception e) {
        }
        return "";
    }

    public static String sendTextPost(String traceId, String url, String param, Map<String, String> header,
                                      int connectTimeoutMilliSeconds, int readTimeoutMilliSeconds,
                                      String reqCharset, String resCharset, boolean isBreak) {
        try {
            if (isBreakRequest() && isBreak) {
                return "";
            }
            OkHttpClient client = builderClient.newBuilder().connectTimeout(connectTimeoutMilliSeconds, TimeUnit.MILLISECONDS).
                    readTimeout(readTimeoutMilliSeconds, TimeUnit.MILLISECONDS).build();
            RequestBody body = RequestBody.create(MediaType.parse("text/plain; charset=" + reqCharset), param.getBytes(reqCharset));
            Request.Builder builder = new Request.Builder()
                    .url(url);
            for (Map.Entry<String, String> kv : header.entrySet()) {
                builder.addHeader(kv.getKey(), kv.getValue());
            }
            Request request = builder.post(body)
                    .build();
            Response response = client.newCall(request).execute(); //execute 同步执行
            return new String(response.body().bytes(), resCharset);
        } catch (Exception e) {
        }
        return "";
    }


    /**
     * @param traceId
     * @param url                        请求url带参数的
     * @param connectTimeoutMilliSeconds 连接超时毫秒数
     * @param readTimeoutMilliSeconds    读取超时毫秒数
     * @param reqCharset                 请求字符集
     * @param resCharset                 响应字符集
     * @param isBreak                    是否支持紧急情况下的手动熔断 和项目的comm配置文件中的request.break=true合并生效
     * @return
     */
    public static String sendTextGet(String traceId, String url, long connectTimeoutMilliSeconds,
                                     long readTimeoutMilliSeconds, String reqCharset, String resCharset, boolean isBreak) {
        try {
            if (isBreakRequest() && isBreak) {
                return "";
            }
            OkHttpClient client = builderClient.newBuilder().connectTimeout(connectTimeoutMilliSeconds, TimeUnit.MILLISECONDS).
                    readTimeout(readTimeoutMilliSeconds, TimeUnit.MILLISECONDS).build();
            Request request = new Request.Builder()
                    .url(url)
                    .addHeader("Content-Type", "text/plain; charset=" + reqCharset)
                    .get()
                    .build();
            Response response = client.newCall(request).execute(); //execute 同步执行
            return new String(response.body().bytes(), resCharset);
        } catch (Exception e) {
            
        }
        return "";
    }

    public static boolean isBreakRequest() {
        return false;
    }

}
